package com.QK.cnstudy.entity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.QK.cnstudy.bean.Quiz;
import com.QK.cnstudy.bean.Subject;

public class Work {
    private int id;
    private int textbookId;
    private int termId;
    private int authorId;
    private String name;
    private String subname;
    private int lastOpentime;
    private int openTimes;

    private Author author;
    private List<Sentence> sentences;
    private List<Word> words;

    public List<Sentence> getSentenceList(SQLiteDatabase db) {
        List<Sentence> sentences = new ArrayList<Sentence>();
        Cursor cursor = null;
        cursor = db.rawQuery("select * from sentence where work_id =?", new String[] { String.valueOf(getId()) });

        while (cursor.moveToNext()) {
            Sentence sentence = new Sentence();
            sentence.setInfoFromCursor(cursor);
            sentences.add(sentence);
        }
        return sentences;
    }

    public String getSentencelist() {
        return "";
    }

    public String getWordlist() {
        return "";
    }

    public Work() {

    }

    /**
     * 根据当前学习的文章，随机创建一套测试题， 最大题数10题
     * 
     * @param db
     * @return
     */
    public Quiz getRandomQuiz(SQLiteDatabase db) {
        Quiz quiz = new Quiz();
        quiz.setTestWorkId(getId());
        List<Sentence> sentences = getSentenceList(db);
        int subjectNum = Math.min(sentences.size(), 10);
        quiz.setSubjectNum(subjectNum);
        List<Subject> subjects = new ArrayList<Subject>();
        for (int i = 0; i < subjectNum; i++) {
            Subject subject = new Subject(sentences, sentences.get(i).getId());
            subjects.add(subject);
        }
        quiz.setSubjects(subjects);
        return quiz;
    }

    public Work(String[] strings) {

    }

    public void setInfoFromCursor(Cursor cursor) {
        int tmp;
        if ((tmp = cursor.getColumnIndex("id")) != -1) {
            setId(cursor.getInt(tmp));
        }
        if ((tmp = cursor.getColumnIndex("textbook_id")) != -1) {
            setTextbookId(cursor.getInt(tmp));
        }
        if ((tmp = cursor.getColumnIndex("term_id")) != -1) {
            setTermId(cursor.getInt(tmp));
        }
        if ((tmp = cursor.getColumnIndex("author_id")) != -1) {
            setAuthorId(cursor.getInt(tmp));
        }
        if ((tmp = cursor.getColumnIndex("last_opentime")) != -1) {
            setLastOpentime(cursor.getInt(tmp));
        }
        if ((tmp = cursor.getColumnIndex("open_times")) != -1) {
            setOpenTimes(cursor.getInt(tmp));
        }

        if ((tmp = cursor.getColumnIndex("name")) != -1) {
            setName(cursor.getString(tmp));
        }
        if ((tmp = cursor.getColumnIndex("subname")) != -1) {
            setSubname(cursor.getString(tmp));
        }
    }

    public void updateWorkRecord(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("update work set last_opentime =? , open_times =? where id=?", new Object[] {
                        (new Date()).getTime(), getOpenTimes() + 1, getId() });
    }

    public void saveToDB(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("insert into work values (?,?,?,?,?,?,?,?)", new Object[] { getId(), getTextbookId(),
                        getTermId(), getAuthorId(), getName(), getSubname(), getLastOpentime(), getOpenTimes() });
    }

    public int getAuthorId() {
        return authorId;
    }

    public void setAuthorId(int authorId) {
        this.authorId = authorId;
    }

    public int getTextbookId() {
        return textbookId;
    }

    public void setTextbookId(int textbookId) {
        this.textbookId = textbookId;
    }

    public int getTermId() {
        return termId;
    }

    public void setTermId(int termId) {
        this.termId = termId;
    }

    public int getLastOpentime() {
        return lastOpentime;
    }

    public void setLastOpentime(int lastOpentime) {
        this.lastOpentime = lastOpentime;
    }

    public int getOpenTimes() {
        return openTimes;
    }

    public void setOpenTimes(int openTimes) {
        this.openTimes = openTimes;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSubname() {
        return subname;
    }

    public void setSubname(String subname) {
        this.subname = subname;
    }

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }

    public List<Sentence> getSentences() {
        return sentences;
    }

    public void setSentences(List<Sentence> sentences) {
        this.sentences = sentences;
    }

    public List<Word> getWords() {
        return words;
    }

    public void setWords(List<Word> words) {
        this.words = words;
    }

    public static List<Word> getWordFromJson(String jsonString) {
        List<Word> words = new ArrayList<Word>();
        JSONTokener jsonParser = new JSONTokener(jsonString);
        try {
            JSONObject workObject = (JSONObject) jsonParser.nextValue();

            int workId = workObject.getInt("id");
            JSONArray wordsArray = workObject.getJSONArray("words");
            for (int i = 0; i < wordsArray.length(); i++) {
                Word word = new Word();
                JSONObject wordObject = wordsArray.optJSONObject(i);
                word.setId(wordObject.getInt("id"));
                word.setContent(wordObject.getString("content"));
                word.setTranslation(wordObject.getString("translation"));
                word.setWorkId(workId);
                word.setMistakeTimes(wordObject.getInt("mistakes"));
                word.setWordtype(wordObject.getInt("kind"));
                words.add(word);
            }
        } catch (JSONException e) {
            Log.v("json error", e.toString());
            e.printStackTrace();
        }
        return words;
    }

    public static List<Sentence> getSentencesFromJson(String jsonString) {
        List<Sentence> sentences = new ArrayList<Sentence>();
        JSONTokener jsonParser = new JSONTokener(jsonString);
        try {
            JSONObject workObject = (JSONObject) jsonParser.nextValue();

            int workId = workObject.getInt("id");
            JSONArray sentencesArray = workObject.getJSONArray("sentences");
            for (int i = 0; i < sentencesArray.length(); i++) {
                Sentence sentence = new Sentence();
                JSONObject sentenceObject = sentencesArray.optJSONObject(i);
                sentence.setId(sentenceObject.getInt("id"));
                sentence.setContent(sentenceObject.getString("content"));
                sentence.setTranslation(sentenceObject.getString("translation"));
                sentence.setWorkId(workId);
                sentences.add(sentence);
            }
        } catch (JSONException e) {
            Log.v("json error", e.toString());
            e.printStackTrace();
        }
        return sentences;
    }

    public static List<Work> getWorksFromJson(String jsonString) {

        List<Work> works = new ArrayList<Work>();
        JSONTokener jsonParser = new JSONTokener(jsonString);
        try {
            JSONArray worksObject = (JSONArray) jsonParser.nextValue();
            for (int i = 0; i < worksObject.length(); i++) {
                Work work = new Work();
                JSONObject workObject = worksObject.optJSONObject(i);
                work.setId(workObject.getInt("id"));
                work.setName(workObject.getString("title"));
                work.setTextbookId(workObject.getJSONObject("textbook").getInt("id"));
                work.setTermId(workObject.getJSONObject("term").getInt("id"));
                Author author = new Author();
                JSONObject authorObject = workObject.getJSONObject("author");
                author.setId(authorObject.getInt("id"));
                author.setName(authorObject.getString("name"));
                author.setInfo(authorObject.getString("detail"));
                work.setAuthorId(author.getId());
                work.setAuthor(author);
                works.add(work);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return works;
    }
}
